package com.gis_luq.lib.Draw;

import java.util.ArrayList;

import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PointF;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;

import com.zondy.mapgis.android.graphic.Graphic;
import com.zondy.mapgis.android.graphic.GraphicMultiPoint;
import com.zondy.mapgis.android.graphic.GraphicPoint;
import com.zondy.mapgis.android.graphic.GraphicPolygon;
import com.zondy.mapgis.android.graphic.GraphicPolylin;
import com.zondy.mapgis.android.graphic.GraphicsOverlay;
import com.zondy.mapgis.android.mapview.MapTool;
import com.zondy.mapgis.android.mapview.MapView;
import com.zondy.mapgis.android.mapview.MapView.MapViewLongTapListener;
import com.zondy.mapgis.android.mapview.MapView.MapViewTapListener;
import com.zondy.mapgis.android.mapview.MapView.MapViewTouchListener;
import com.zondy.mapgis.core.geometry.Dot;

/**
 * 
 * @author ropp gispace@yeah.net update by gis-luq
 *         画图实现类，支持画点、矩形、线、多边形、圆、手画线、手画多边形，可设置各种图形的symbol。
 */
public class DrawTool extends Subject
{

	private static String TAG = "DrawTool";

	private MapView mMapView;
	private GraphicsOverlay mGraphicsLayerEditing;// 绘制要素图层
	private GraphicsOverlay tempLayer;// 零时图层，用于存储要素各个节点信息
	private int drawType;// 当前要素绘制类型
	private boolean active;
	private boolean isAllowDoubleTouchToEnd = true;// 是否允许双击结束绘制
	private Point point;
	// private Envelope envelope;
	// private Polyline polyline;
	// private Polygon polygon;
	private DrawTouchListener drawListener;// 绘图事件
	private Graphic drawGraphic;// 当前绘制要素
	private Point startPoint;// 当前绘制要素起点信息
	private int graphicID;// 当前绘制要素graphicID

	private boolean isCompleteDraw = true;// 是否完成要素绘制

	// =======================================================================================================
	ArrayList<Point> mPoints = new ArrayList<Point>(); // 节点
	ArrayList<Point> mMidPoints = new ArrayList<Point>(); // 中间点
	boolean mMidPointSelected = false; // 线段中间点
	boolean mVertexSelected = false;// 顶点是否选择
	int mInsertingIndex;// 插入位置信息
	ArrayList<EditingStates> mEditingStates = new ArrayList<EditingStates>();// 编辑状态信息

	ArrayList<Dot> mDots = new ArrayList<Dot>();
	ArrayList<Dot> mMidDots = new ArrayList<Dot>();
	ArrayList<GraphicPoint> mGraphicPointLst = new ArrayList<GraphicPoint>();
	GraphicMultiPoint mGraphicMultiPoint = null;// 点
	GraphicPolylin mGraphicPolylin = null;
	GraphicPolygon mGraphicPolygon = null;
	private GestureDetector mGestureDetector;

	public static final int POINT = 1;// 点
	public static final int ENVELOPE = 2;// 矩形
	public static final int POLYLINE = 3;// 线
	public static final int POLYGON = 4;// 面
	public static final int CIRCLE = 5;// 圆
	public static final int ELLIPSE = 6;// 椭圆
	public static final int FREEHAND_POLYGON = 7; // 流状面
	public static final int FREEHAND_POLYLINE = 8; // 流状线

	public DrawTool(MapView mapView)
	{
		this.mMapView = mapView;
		// this.mapmMapViewtShowMagnifierOnLongPress(true);//允许使用放大镜
		// this.mapView.setShowMagnifierOnLongPress(true);
		this.mGraphicsLayerEditing = new GraphicsOverlay();
		this.mMapView.getGraphicsOverlays().add(mGraphicsLayerEditing);
		this.tempLayer = new GraphicsOverlay();
		this.mMapView.getGraphicsOverlays().add(tempLayer);
		mGestureDetector = new GestureDetector(gestureListen);

	}

	public void activate(int drawType)
	{
		if (this.mMapView == null)
			return;

		this.deactivate();

		// mapView.setOnTouchListener(drawListener);
		// mMapView.setTouchListener(drawListener);
		mMapView.setTouchListener(mapViewTouchListen);
		mMapView.setTapListener(mapTapListen);
		mMapView.setLongTapListener(mapViewLongTapListen);
		this.drawType = drawType;
		this.active = true;
		switch (this.drawType) 
		{
		case DrawTool.POINT:
			if (mGraphicMultiPoint == null)
			{
				mGraphicMultiPoint = new GraphicMultiPoint();
				mGraphicMultiPoint.setColor(Color.argb(255, 0, 0, 255));
				mGraphicMultiPoint.setPointSize(12);
				mGraphicMultiPoint.setPoints(mDots);
			}

			mGraphicsLayerEditing.addGraphic(mGraphicMultiPoint);
			break;
		case DrawTool.ENVELOPE:
			// this.envelope = new Envelope();
			// drawGraphic = new Graphic(this.envelope, this.fillSymbol);
			break;
		case DrawTool.POLYGON:
			if (mGraphicPolygon == null)
			{
				mGraphicPolygon = new GraphicPolygon();
				// mGraphicPolygon.setColor(Color.BLACK);
				mGraphicPolygon.setBorderlineWidth(6);
				mGraphicPolygon.setPoints(mDots);
			}
			mGraphicsLayerEditing.addGraphic(mGraphicPolygon);
			break;
		case DrawTool.CIRCLE:
		case DrawTool.FREEHAND_POLYGON:
			// this.polygon = new Polygon();
			// drawGraphic = new Graphic(this.polygon, this.fillSymbol);
			// clear();//清除顶点和节点信息
			break;
		case DrawTool.POLYLINE:
			if (mGraphicPolylin == null)
			{
				mGraphicPolylin = new GraphicPolylin();
				mGraphicPolylin.setColor(Color.BLACK);
				mGraphicPolylin.setLineWidth(6);
				mGraphicPolylin.setPoints(mDots);
			}
			mGraphicsLayerEditing.addGraphic(mGraphicPolylin);
			drawGraphic = mGraphicPolylin;
			break;
		case DrawTool.FREEHAND_POLYLINE:
			// this.polyline = new Polyline();
			// drawGraphic = new Graphic(this.polyline, this.lineSymbol);
			// clear();//清除顶点和节点信息
			break;
		}

		isCompleteDraw = false;// 开始绘制
	}

	public void deactivate()
	{
		// this.mGraphicsLayerEditing.removeAllGraphics();
		this.tempLayer.removeAllGraphics();
		this.active = false;
		this.isCompleteDraw = true;// 完成绘制
		this.drawType = -1;
		mDots.clear();
		mGraphicPolylin = null;
		mGraphicMultiPoint = null;
		mGraphicPolygon = null;

		// this.point = null;
		// this.envelope = null;
		// this.polygon = null;
		// this.polyline = null;
		// this.drawGraphic = null;
		// this.startPoint=null;
	}

	public boolean isActive()
	{
		return this.active;
	}

	public boolean isCompleteDraw()
	{
		return this.isCompleteDraw;
	}

	// 设置是否允许双击结束
	public void setAllowDoubleTouchToEnd(Boolean isAllowDoubleTouchToEnd)
	{
		this.isAllowDoubleTouchToEnd = isAllowDoubleTouchToEnd;
	}

	public void sendDrawEndEvent()
	{

		DrawEvent e = new DrawEvent(this, DrawEvent.DRAW_END, DrawTool.this.mGraphicsLayerEditing.getGraphic(mGraphicsLayerEditing.getGraphicCount() - 1));
		DrawTool.this.notifyEvent(e);
		int type = this.drawType;
		this.deactivate();
		if (type == POINT)
		{
			this.activate(type);
		}
	}

	/**
	 * 设置当前待编辑 该编辑目前仅经针对线、面编辑情况
	 */
	// public void setEditGraphic(Graphic graphic){
	// this.mGraphicsLayerEditing.removeAll();
	// Geometry geometry = graphic.getGeometry();
	// if(geometry!=null){
	// Geometry.Type type = geometry.getType();
	// if(type== Geometry.Type.POINT||type== Geometry.Type.MULTIPOINT){//点
	// //不执行任何操作
	// }else if(type== Geometry.Type.LINE||type== Geometry.Type.POLYLINE){//线
	//
	// this.activate(DrawTool.POLYLINE);
	// //获取点并按指定显示在地图上
	// Graphic graphic1 = new Graphic(geometry,DrawSymbol.mLineSymbol);
	// graphicID =this.mGraphicsLayerEditing.addGraphic(graphic1);
	// this.drawGraphic = graphic1;//保存当前
	// MultiPath polyline = (MultiPath)graphic1.getGeometry();
	// this.mPoints.clear();
	// for (int i =0;i<polyline.getPointCount();i++){
	// Point pt = polyline.getPoint(i);
	// this.mPoints.add(pt);
	// }
	// refresh();
	//
	// }else if(type== Geometry.Type.ENVELOPE||type== Geometry.Type.POLYGON){//面
	//
	// this.activate(DrawTool.POLYGON);
	// //获取点并按指定显示在地图上
	// Graphic graphic1 = new Graphic(geometry,DrawSymbol.mFillSymbol);
	// graphicID =this.mGraphicsLayerEditing.addGraphic(graphic1);
	// this.drawGraphic = graphic1;//保存当前
	// MultiPath polygon = (MultiPath)graphic1.getGeometry();
	// this.mPoints.clear();
	// for(int i =0;i<polygon.getPointCount();i++){
	// Point pt = polygon.getPoint(i);
	// this.mPoints.add(pt);
	// }
	// refresh();
	//
	// }else if(type== Geometry.Type.UNKNOWN){//未知
	//
	// }else{//type不在区间内
	//
	// }
	// }
	//
	// }

	/**
	 * 刷新要素信息
	 */
	private void refresh()
	{
		if (tempLayer != null)
		{
			tempLayer.removeAllGraphics();
		}
		// drawPolylineOrPolygon();
		mGraphicPolylin.setPoints(mDots);

		drawMidPoints(); // 绘制要素中心点
		drawVertices(); // 绘制要素节点
		mMapView.refresh();
	}

	/**
	 * 绘制节点的中心点
	 */
	private void drawMidPoints()
	{
		int index;
		GraphicPoint graphic;

		mMidDots.clear();
		if (mDots.size() > 1)
		{

			// Build new list of mid-points
			for (int i = 1; i < mDots.size(); i++)
			{
				Dot p1 = mDots.get(i - 1);
				Dot p2 = mDots.get(i);
				mMidDots.add(new Dot((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2));
			}
			// if (drawType == POLYGON && mDots.size() > 2)
			// {
			// // Complete the circle
			// Point p1 = mDots.get(0);
			// Point p2 = mDots.get(mDots.size() - 1);
			// mMidPoints.add(new Point((p1.getX() + p2.getX()) / 2, (p1.getY()
			// + p2.getY()) / 2));
			// }

			// Draw the mid-points
			index = 0;
			for (Dot dot : mMidDots)
			{
				if (mMidPointSelected && mInsertingIndex == index)
				{
					graphic = new GraphicPoint(dot, 12);
					graphic.setColor(Color.RED);
				}
				else
				{
					graphic = new GraphicPoint(dot, 12);
					graphic.setColor(Color.GREEN);
				}
				this.tempLayer.addGraphic(graphic);
				index++;
			}
		}
	}

	/**
	 * 绘制要素的节点信息在mPoints中.
	 */
	private void drawVertices()
	{
		int index = 0;

		for (Dot dot : mDots)
		{
			GraphicPoint graphicPoint = new GraphicPoint(dot, 12);

			if (mVertexSelected && index == mInsertingIndex)
			{
				// This vertex is currently selected so make it red
				graphicPoint.setColor(Color.RED);
			}
			else if (index == mDots.size() - 1 && !mMidPointSelected && !mVertexSelected)
			{
				// Last vertex and none currently selected so make it red
				graphicPoint.setColor(Color.RED);
			}
			else
			{
				// Otherwise make it black
				graphicPoint.setColor(Color.BLACK);
			}
			tempLayer.addGraphic(graphicPoint);// 添加节点信息到零时图层
			index++;
		}
	}

	/**
	 * 清除节点和终点信息
	 */
	private void clear()
	{
		// 清除要素编辑状态数据
		mDots.clear();
		mMidDots.clear();
		mEditingStates.clear();

		mMidPointSelected = false;
		mVertexSelected = false;
		mInsertingIndex = 0;

		if (tempLayer != null)
		{
			tempLayer.removeAllGraphics();
		}
	}

	/**
	 * 通过mPoints中的顶点绘制折线和多边形.
	 */
	// private void drawPolylineOrPolygon() {
	// MultiPath multipath;
	// if (mPoints.size() >= 1) {
	// //利用节点信息创建MultiPath信息
	// if (drawType == POLYLINE) {
	// multipath = new Polyline();
	// } else {
	// multipath = new Polygon();
	// }
	// multipath.startPath(mPoints.get(0));
	// for (int i = 1; i < mPoints.size(); i++) {
	// multipath.lineTo(mPoints.get(i));
	// }
	// //创建多段线或者面
	// if (drawType == POLYLINE) {
	// this.drawGraphic = new Graphic(multipath, DrawSymbol.mLineSymbol);
	// polyline = (Polyline) multipath;//保存线数据到全局变量
	// } else {
	// this.drawGraphic = new Graphic(multipath,DrawSymbol.mFillSymbol);
	// polygon = (Polygon) multipath;//保存面数据到全局变量
	// }
	// this.mGraphicsLayerEditing.updateGraphic(graphicID, this.drawGraphic);
	// }
	// }

	/**
	 * 节点回退操作.
	 */
	public boolean actionUndo()
	{
		if (active && (drawType == POLYGON || drawType == POLYLINE))
		{
			if (mDots.size() >= 1)
			{// 删除时至少保留一个节点
				if (mEditingStates.size() >= 1)
				{
					if (mEditingStates.size() == 0)
					{
						mMidPointSelected = false;
						mVertexSelected = false;
						mInsertingIndex = 0;
					}
					else
					{
						mDots.clear();// 清空节点要素
						EditingStates state = mEditingStates.get(mEditingStates.size() - 1);
						mDots.addAll(state.dots);
						// Log.d(TAG, "# of points = " + mPoints.size());
						mMidPointSelected = state.midPointSelected;
						mVertexSelected = state.vertexSelected;
						mInsertingIndex = state.insertingIndex;
						refresh();
						mEditingStates.remove(mEditingStates.size() - 1);
						Toast.makeText(mMapView.getContext(), "撤销操作", Toast.LENGTH_SHORT).show();
						return true;
					}
				}
				else
				{
					Toast.makeText(mMapView.getContext(), "当前状态无法撤销", Toast.LENGTH_SHORT).show();
				}
			}
		}
		return false;
	}

	/**
	 * 节点删除操作.
	 */
	public boolean actionDelete()
	{
		if (active && (drawType == POLYGON || drawType == POLYLINE))
		{
			if (mDots.size() >= 2)
			{
				if (!mVertexSelected)
				{
					mDots.remove(mDots.size() - 1); // 删除最后一个顶点
				}
				else
				{
					mDots.remove(mInsertingIndex); // 删除当前选择的点
				}

				// 删除时至少保留一个节点
				mMidPointSelected = false;
				mVertexSelected = false;
				mEditingStates.add(new EditingStates(mDots, mMidPointSelected, mVertexSelected, mInsertingIndex));

				refresh();
				Toast.makeText(mMapView.getContext(), "删除节点", Toast.LENGTH_SHORT).show();
				return true;
			}
			else
			{
				Toast.makeText(mMapView.getContext(), "当前已无法删除节点", Toast.LENGTH_SHORT).show();
			}

		}
		return false;
	}
	
	/**
	 * Checks if a given location coincides (within a tolerance) with a point in
	 * a given array.
	 * 
	 * @param x Screen coordinate of location to check.
	 * @param y Screen coordinate of location to check.
	 * @param points Array of points to check.
	 * @param map MapView containing the points.
	 * @return Index within points of matching point, or -1 if none.
	 */
	private int getSelectedIndex(double x, double y, ArrayList<Dot> dots, MapView map)
	{
		final int TOLERANCE = 40; // Tolerance in pixels

		if (dots == null || dots.size() == 0)
		{
			return -1;
		}

		// Find closest point
		int index = -1;
		double distSQ_Small = Double.MAX_VALUE;
		for (int i = 0; i < dots.size(); i++)
		{
			PointF p = mMapView.mapPointToViewPoint(dots.get(i));
			double diffx = p.x - x;
			double diffy = p.y - y;
			double distSQ = diffx * diffx + diffy * diffy;
			if (distSQ < distSQ_Small)
			{
				index = i;
				distSQ_Small = distSQ;
			}
		}

		// Check if it's close enough
		if (distSQ_Small < (TOLERANCE * TOLERANCE))
		{
			return index;
		}
		return -1;
	}

	/**
	 * 移动当前选择点
	 * 
	 * @param point Location to move the point to.
	 */
	private void movePoint(Dot dot)
	{
		if (mMidPointSelected)
		{
			// Move mid-point to the new location and make it a vertex
			mDots.add(mInsertingIndex + 1, dot);
		}
		else
		{
			// Must be a vertex: move it to the new location
			ArrayList<Dot> temp = new ArrayList<Dot>();
			for (int i = 0; i < mDots.size(); i++)
			{
				if (i == mInsertingIndex)
				{
					temp.add(dot);
				}
				else
				{
					temp.add(mDots.get(i));
				}
			}
			mDots.clear();
			mDots.addAll(temp);
		}
		// Go back to the normal drawing mode and save the new editing state
		mMidPointSelected = false;
		mVertexSelected = false;
		mEditingStates.add(new EditingStates(mDots, mMidPointSelected, mVertexSelected, mInsertingIndex));
	}
	

	/**
	 * 扩展MapOnTouchListener，实现画图功能
	 */
	class DrawTouchListener implements MapViewTouchListener
	{

		// public DrawTouchListener(Context context, MapView view) {
		// super(context, view);
		// }

		// @Override
		// public boolean onDragPointerMove(MotionEvent from, MotionEvent to) {
		// if (active
		// && (drawType == ENVELOPE || drawType == FREEHAND_POLYGON
		// || drawType == FREEHAND_POLYLINE || drawType == CIRCLE)) {
		// //检查是否为空
		// if(from==null||to==null) return false;
		// Point point = mapView.toMapPoint(to.getX(), to.getY());
		// switch (drawType) {
		// case DrawTool.ENVELOPE:
		// envelope.setXMin(startPoint.getX() > point.getX() ? point
		// .getX() : startPoint.getX());
		// envelope.setYMin(startPoint.getY() > point.getY() ? point
		// .getY() : startPoint.getY());
		// envelope.setXMax(startPoint.getX() < point.getX() ? point
		// .getX() : startPoint.getX());
		// envelope.setYMax(startPoint.getY() < point.getY() ? point
		// .getY() : startPoint.getY());
		// DrawTool.this.mGraphicsLayerEditing.updateGraphic(graphicID,
		// envelope.copy());
		// break;
		// case DrawTool.FREEHAND_POLYGON:
		// polygon.lineTo(point);
		// DrawTool.this.mGraphicsLayerEditing.updateGraphic(graphicID,
		// polygon);
		//
		// break;
		// case DrawTool.FREEHAND_POLYLINE:
		// polyline.lineTo(point);
		// DrawTool.this.mGraphicsLayerEditing.updateGraphic(graphicID,
		// polyline);
		//
		// break;
		// case DrawTool.CIRCLE:
		// double radius = Math.sqrt(Math.pow(startPoint.getX()
		// - point.getX(), 2)
		// + Math.pow(startPoint.getY() - point.getY(), 2));
		// getCircle(startPoint, radius, polygon);
		// DrawTool.this.mGraphicsLayerEditing.updateGraphic(graphicID,
		// polygon);
		// break;
		// }
		// return true;
		// }
		// return super.onDragPointerMove(from, to);
		// }

		// @Override
		// public boolean onDragPointerUp(MotionEvent from, MotionEvent to) {
		// if (active && (drawType == ENVELOPE || drawType == FREEHAND_POLYGON
		// || drawType == FREEHAND_POLYLINE || drawType == CIRCLE)) {
		// //检查是否为空
		// if(from==null||to==null) return false;
		// Point point = mapView.toMapPoint(to.getX(), to.getY());
		// switch (drawType) {
		// case DrawTool.ENVELOPE:
		// envelope.setXMin(startPoint.getX() > point.getX() ? point
		// .getX() : startPoint.getX());
		// envelope.setYMin(startPoint.getY() > point.getY() ? point
		// .getY() : startPoint.getY());
		// envelope.setXMax(startPoint.getX() < point.getX() ? point
		// .getX() : startPoint.getX());
		// envelope.setYMax(startPoint.getY() < point.getY() ? point
		// .getY() : startPoint.getY());
		// break;
		// case DrawTool.FREEHAND_POLYGON://流状面
		// polygon.lineTo(point);
		// break;
		// case DrawTool.FREEHAND_POLYLINE://流状线
		// polyline.lineTo(point);
		// break;
		// case DrawTool.CIRCLE:
		// double radius = Math.sqrt(Math.pow(startPoint.getX()
		// - point.getX(), 2)
		// + Math.pow(startPoint.getY() - point.getY(), 2));
		// getCircle(startPoint, radius, polygon);
		// break;
		// }
		// sendDrawEndEvent();
		// startPoint = null;
		// isCompleteDraw=true;//开始绘制
		// return true;
		// }
		// return super.onDragPointerUp(from, to);
		// }

		// @Override
		// public boolean onSingleTap(MotionEvent event) {
		// if(active&&(drawType == POINT || drawType == POLYLINE || drawType ==
		// POLYGON)){
		// return handleTap(event);
		// }
		// return super.onSingleTap(event);
		// }

		// @Override
		// public boolean onLongPressUp(MotionEvent event) {
		// if(active&&(drawType == POINT || drawType == POLYLINE || drawType ==
		// POLYGON)){
		// return handleTap(event);
		// }
		// return super.onLongPressUp(event);
		// }

		// @Override
		// public boolean onDoubleTap(MotionEvent event) {
		// if (active &&(drawType==POLYGON || drawType==POLYLINE)) {
		// // Point point = mapView.toMapPoint(event.getX(), event.getY());
		// // //双击最后一个点不算在内
		// // switch (drawType) {
		// // case DrawTool.POLYGON:
		// // polygon.lineTo(point);
		// // break;
		// // case DrawTool.POLYLINE:
		// // polyline.lineTo(point);
		// // break;
		// // }
		// int ptNum = mPoints.size();
		// if(drawType==POLYLINE){
		// if(ptNum<2){
		// Toast.makeText(mapView.getContext(), "线段至少两个节点",
		// Toast.LENGTH_SHORT).show();
		// return true;
		// }
		// }else if (drawType==POLYGON){
		// if(ptNum<3){
		// Toast.makeText(mapView.getContext(), "面至少三个节点",
		// Toast.LENGTH_SHORT).show();
		// return true;
		// }
		// }
		// isCompleteDraw=true;//开始绘制
		// if(isAllowDoubleTouchToEnd){
		// sendDrawEndEvent();
		// startPoint = null;
		// }
		// return true;
		// }
		// return super.onDoubleTap(event);
		// }

		/***
		 * Handle a tap on the map (or the end of a magnifier long-press event).
		 * 
		 * @param event The point that was tapped.
		 */
		// private boolean handleTap(MotionEvent event) {
		// Point point = mapView.toMapPoint(event.getX(), event.getY());
		// if (active && (drawType==POLYGON || drawType==POLYLINE)) {
		// // If a point is currently selected, move that point to tap point
		// if (mMidPointSelected || mVertexSelected) {
		// movePoint(point);
		// } else {
		// // If tap coincides with a mid-point, select that mid-point
		// int idx1 = getSelectedIndex(event.getX(), event.getY(), mMidPoints,
		// mapView);
		// if (idx1 != -1) {
		// mMidPointSelected = true;
		// mInsertingIndex = idx1;
		// } else {
		// // If tap coincides with a vertex, select that vertex
		// int idx2 = getSelectedIndex(event.getX(), event.getY(), mPoints,
		// mapView);
		// if (idx2 != -1) {
		// mVertexSelected = true;
		// mInsertingIndex = idx2;
		// } else {
		// // No matching point above, add new vertex at tap point
		// mEditingStates.add(new EditingStates(mPoints, mMidPointSelected,
		// mVertexSelected, mInsertingIndex));
		// mPoints.add(point);
		// }
		// }
		// }
		// refresh();
		// return true;
		// }else if(drawType==POINT ){
		// DrawTool.this.point.setXY(point.getX(), point.getY());
		// sendDrawEndEvent();
		// isCompleteDraw=true;//开始绘制
		// return true;
		// }
		// return false;//默认为false
		// }

		@Override
		public boolean mapViewTouch(MotionEvent event)
		{
			if (active && (drawType == ENVELOPE || drawType == CIRCLE || drawType == FREEHAND_POLYLINE || drawType == FREEHAND_POLYGON)
					&& event.getAction() == MotionEvent.ACTION_DOWN)
			{
				// 检查是否为空
				if (event == null)
					return false;
				// Point point = mapView.toMapPoint(event.getX(), event.getY());
				PointF pointF = new PointF(event.getX(), event.getY());
				Dot dot = mMapView.viewPointToMapPoint(pointF);
				switch (drawType)
				{
				case DrawTool.POINT:
					// DrawTool.this.point.setXY(point.getX(), point.getY());
					// sendDrawEndEvent();
					// mDots.add(dot);
					break;
				case DrawTool.ENVELOPE:
					startPoint = point;
					// envelope.setCoords(point.getX(), point.getY(),
					// point.getX(), point.getY());
					break;
				case DrawTool.CIRCLE:
					// startPoint = point;
					break;
				case DrawTool.FREEHAND_POLYGON:
					// polygon.startPath(point);
					break;
				case DrawTool.FREEHAND_POLYLINE:
					// polyline.startPath(point);
					break;
				}
				return true;
			}
			try
			{
				// 多次执行面分割会异常
				// return super.onTouch(view, event);
			}
			catch (Exception e)
			{
				Log.e(TAG, e.getMessage());
				return true;
			}

			return false;
		}
	}

	MapViewTapListener mapTapListen = new MapViewTapListener()
	{
		@Override
		public void mapViewTap(PointF viewPoint)
		{
			Dot dot = mMapView.viewPointToMapPoint(viewPoint);
			if (active && drawType == POLYLINE)
			{
				// If a point is currently selected, move that point to tap
				// point
				if (mMidPointSelected || mVertexSelected)
				{
					movePoint(dot);
				}
				else
				{
					// If tap coincides with a mid-point, select that mid-point
					int idx1 = getSelectedIndex(viewPoint.x, viewPoint.y, mMidDots, mMapView);
					if (idx1 != -1)
					{
						mMidPointSelected = true;
						mInsertingIndex = idx1;
						 mMapView.setMapTool(mapTool);
					}
					else
					{
						// If tap coincides with a vertex, select that vertex
						int idx2 = getSelectedIndex(viewPoint.x, viewPoint.y, mDots, mMapView);
						if (idx2 != -1)
						{
							mVertexSelected = true;
							mInsertingIndex = idx2;
							 mMapView.setMapTool(mapTool);
						}
						else
						{
							// No matching point above, add new vertex at tap
							// point
							mEditingStates.add(new EditingStates(mDots, mMidPointSelected, mVertexSelected, mInsertingIndex));
							mDots.add(dot);
						}
					}
				}

				// mDots.add(dot);
				refresh();
			}
			else
			{
				mDots.add(dot);
				mGraphicMultiPoint.setPoints(mDots);
			}
			mMapView.refresh();
		}
	};
	
	MapViewLongTapListener mapViewLongTapListen = new MapViewLongTapListener()
	{
		
		@Override
		public boolean mapViewLongTap(PointF viewPoint)
		{

			Dot dot = mMapView.viewPointToMapPoint(viewPoint);
			if (active && drawType == POLYLINE)
			{
				// If a point is currently selected, move that point to tap
				// point
				if (mMidPointSelected || mVertexSelected)
				{
					// mMapView.setMapTool(mapTool);
					movePoint(dot);
				}
				else
				{
					// If tap coincides with a mid-point, select that mid-point
					int idx1 = getSelectedIndex(viewPoint.x, viewPoint.y, mMidDots, mMapView);
					if (idx1 != -1)
					{
						mMidPointSelected = true;
						mInsertingIndex = idx1;
					}
					else
					{
						// If tap coincides with a vertex, select that vertex
						int idx2 = getSelectedIndex(viewPoint.x, viewPoint.y, mDots, mMapView);
						if (idx2 != -1)
						{
							mVertexSelected = true;
							mInsertingIndex = idx2;
						}
						else
						{
							// No matching point above, add new vertex at tap
							// point
							mEditingStates.add(new EditingStates(mDots, mMidPointSelected, mVertexSelected, mInsertingIndex));
							mDots.add(dot);
						}
					}
				}

				// mDots.add(dot);
				refresh();
			}
			else
			{
				mDots.add(dot);
				mGraphicMultiPoint.setPoints(mDots);
			}
			mMapView.refresh();
		
			return false;
		}
	};

	MapViewTouchListener mapViewTouchListen = new MapViewTouchListener()
	{

		@Override
		public boolean mapViewTouch(MotionEvent event)
		{
			mGestureDetector.onTouchEvent(event);
			return false;
		}
	};

	MapTool mapTool = new MapTool()
	{

		@Override
		public boolean zoomAndRotateStateEnded(MotionEvent event, MapView mapView, float scale, float angle)
		{
			return false;
		}

		@Override
		public boolean zoomAndRotateStateChanged(MotionEvent event, MapView mapView, float scale, float angle)
		{
			return false;
		}

		@Override
		public boolean zoomAndRotateStateBegan(MotionEvent event, MapView mapView)
		{
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void tap(MotionEvent event, MapView mapView)
		{
			
		}

		@Override
		public boolean panStateEnded(MotionEvent event, MapView mapView, float velocityX, float velocityY)
		{
			PointF viewPoint = new PointF(event.getX(), event.getY());
			Dot dot = mMapView.viewPointToMapPoint(viewPoint);
			if (mMidPointSelected || mVertexSelected)
			{
				movePoint(dot);
			}
			refresh();
			mMapView.setMapTool(null);
			return false;
		}

		@Override
		public boolean panStateChanged(MotionEvent event, MapView mapView)
		{
			PointF viewPoint = new PointF(event.getX(), event.getY());
			Dot dot = mMapView.viewPointToMapPoint(viewPoint);
			movePoint(dot);
			refresh();
			return false;
		}

		@Override
		public boolean panStateBegan(MotionEvent event, MapView mapView)
		{

			PointF viewPoint = new PointF(event.getX(), event.getY());
			Dot dot = mMapView.viewPointToMapPoint(viewPoint);
			if (active && drawType == POLYLINE)
			{
				movePoint(dot);
				refresh();
			}
			else
			{
				mDots.add(dot);
				mGraphicMultiPoint.setPoints(mDots);
			}
			mMapView.refresh();

			return false;
		}

		@Override
		public boolean longTap(MotionEvent event, MapView mapView)
		{
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean doubleTap(MotionEvent event, MapView mapView)
		{
			// TODO Auto-generated method stub
			return false;
		}
	};

	android.view.GestureDetector.OnGestureListener gestureListen = new GestureDetector.OnGestureListener()
	{

		@Override
		public boolean onSingleTapUp(MotionEvent e)
		{
			Log.e("onSingleTapUp", e.getX()+"e1:"+e.getY());
			return false;
		}

		@Override
		public void onShowPress(MotionEvent e)
		{
			// TODO Auto-generated method stub

		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
		{
			Log.e("onScroll", e1.getX()+"e1:"+e1.getY());
			Log.e("onScroll", e2.getX()+"e2:"+e2.getY());

			PointF viewPoint = new PointF(e1.getX(), e1.getY());
			Dot dot = mMapView.viewPointToMapPoint(viewPoint);
			// If tap coincides with a mid-point, select that mid-point
			int idx1 = getSelectedIndex(viewPoint.x, viewPoint.y, mMidDots, mMapView);
			if (idx1 != -1)
			{
				mMidPointSelected = true;
				mInsertingIndex = idx1;
//				 mMapView.setMapTool(mapTool);
			}
			else
			{
				// If tap coincides with a vertex, select that vertex
				int idx2 = getSelectedIndex(viewPoint.x, viewPoint.y, mDots, mMapView);
				if (idx2 != -1)
				{
					mVertexSelected = true;
					mInsertingIndex = idx2;
//					 mMapView.setMapTool(mapTool);
				}
				else
				{
					// No matching point above, add new vertex at tap
					// point
//					mEditingStates.add(new EditingStates(mDots, mMidPointSelected, mVertexSelected, mInsertingIndex));
//					mDots.add(dot);
				}
			}
			refresh();
		
			return false;
		}

		@Override
		public void onLongPress(MotionEvent e)
		{

		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
		{
			Log.e("onFling", e1.getX()+"e1:"+e1.getY());
			Log.e("onFling", e2.getX()+"e2:"+e2.getY());
			return false;
		}

		@Override
		public boolean onDown(MotionEvent e)
		{
			// TODO Auto-generated method stub
			return false;
		}
	};

	/**
	 * 绘制圆
	 * 
	 * @param center
	 * @param radius
	 * @param circle
	 */
	// private void getCircle(Point center, double radius, Polygon circle) {
	// circle.setEmpty();
	// Point[] points = getPoints(center, radius);
	// circle.startPath(points[0]);
	// for (int i = 1; i < points.length; i++)
	// circle.lineTo(points[i]);
	// }

	// private Point[] getPoints(Point center, double radius) {
	// Point[] points = new Point[50];
	// double sin;
	// double cos;
	// double x;
	// double y;
	// for (double i = 0; i < 50; i++) {
	// sin = Math.sin(Math.PI * 2 * i / 50);
	// cos = Math.cos(Math.PI * 2 * i / 50);
	// x = center.getX() + radius * sin;
	// y = center.getY() + radius * cos;
	// points[(int) i] = new Point(x, y);
	// }
	// return points;
	// }

}
